package com.bytedance.common.utility.b;

import com.bytedance.common.utility.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPlus implements Runnable {
    static final ExecutorService CACHED_EXECUTOR = Executors.newCachedThreadPool(new ThreadPlusThreadFactory("ThreadPlus-cached", true));
    static final ExecutorService FIXED_EXECUTOR = Executors.newFixedThreadPool(5, new ThreadPlusThreadFactory("ThreadPlus-fixed", true));
    private final boolean mBackground;
    private Runnable runnable;
    protected static final AtomicInteger sCount = new AtomicInteger();

    public ThreadPlus() {
        this(false);
    }

    public ThreadPlus(boolean background) {
        this.mBackground = background;
    }

    public ThreadPlus(Runnable runnable, String name, boolean background) {
        this.runnable = runnable;
        this.mBackground = background;
    }

    public ThreadPlus(String name) {
        this(false);
    }

    public void run() {
        if (this.runnable != null) {
            this.runnable.run();
        }
    }

    public static void shutdown() {
        ThreadPlus.CACHED_EXECUTOR.shutdown();
        ThreadPlus.FIXED_EXECUTOR.shutdown();
    }

    public void start() {
        Runnable runnable;
        if (Logger.debug()) {
            runnable = new Runnable() {
                public final void run() {
                    Logger.d("ThreadPlus", "thread count: " + ThreadPlus.sCount.incrementAndGet());
                    try {
                        ThreadPlus.this.run();
                    } catch (Exception e) {
                        Logger.w("ThreadPlus", "Thread crashed!", ((Throwable) e));
                    }
                    Logger.d("ThreadPlus", "thread count: " + ThreadPlus.sCount.decrementAndGet());
                }
            };
        } else {
            runnable = this;
        }

        if (this.mBackground) {
            ThreadPlus.FIXED_EXECUTOR.submit(runnable);
        } else {
            ThreadPlus.CACHED_EXECUTOR.submit(runnable);
        }
    }

    public static void submitRunnable(Runnable runnable) {
        if (runnable != null) {
            ThreadPlus.CACHED_EXECUTOR.submit(runnable);
        }
    }
}

